class Solution
{
public:
    int minOperations(vector<int> &nums, int x)
    {
        int n = nums.size();
        int partialSum = 0;
        unordered_map<int, int> partialSumIndex;
        partialSumIndex[0] = -1;
        for (int i = 0; i < n; ++i)
        {
            partialSum += nums[i];
            if (!partialSumIndex.count(partialSum))
            {
                partialSumIndex[partialSum] = i;
            }
        }
        int minOp = INT_MAX;
        if (partialSumIndex.count(x))
        {
            minOp = partialSumIndex[x] + 1;
        }
        int tailPartialSum = 0;
        for (int i = n - 1; i > 0; --i)
        {
            tailPartialSum += nums[i];
            int remain = x - tailPartialSum;
            if (partialSumIndex.count(remain) && partialSumIndex[remain] < i)
            {
                minOp = min(minOp, n - i + partialSumIndex[remain] + 1);
            }
        }
        return minOp == INT_MAX ? -1 : minOp;
    }
};